<template>
  <div></div>
</template>


<script>
import {getToken} from "@/utils/auth";

export default {
  name: 'WebSocket',

  data() {
    return {
      WebSocket: undefined,
      wsUrl: undefined,
      // 是否真正建立连接
      lockReconnect: false,
      // 60 秒一次心跳
      timeout: 60 * 1000,
      // 时间间隔对象
      timeObject: undefined,
      // 心跳倒计时对象
      serverTimeObject: undefined,
      // 重连对象
      timeOutNum: undefined
    };
  },
  created() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() {
      this.initWebSocketUri();
      // 建立链接
      if (typeof (WebSocket) === 'undefined') {
        console.log('浏览器不支持 WebSocket')
      } else {
        this.webSocket = new WebSocket(this.wsUrl);
        console.log("this.websocket", this.webSocket)
        this.webSocket.onopen = this.webSocketOnOpen
        this.webSocket.onerror = this.webSocketOnError
        this.webSocket.onmessage = this.webSocketOnMessage
        this.webSocket.onclose = this.webSocketOnClose
      }
    },
    initWebSocketUri() {
      this.wsUrl = 'ws://127.0.0.1:8080/websocket/' + getToken()
    },
    webSocketOnOpen() {
      console.log('连接成功')
      // 开启心跳
      this.start();
    },
    webSocketOnMessage(message) {
      console.log('服务器发来消息：', message);
      this.reSet()
    },
    webSocketOnClose() {
      console.log('连接关闭');
      this.reConnect();
    },
    webSocketOnError() {
      console.log('连接出错')
      this.reConnect();
    },
    start() {
      this.timeObject && clearTimeout(this.timeObject);
      this.serverTimeObject && clearTimeout(this.serverTimeObject);
      this.timeObject = setTimeout(() => {
        // 连接正常
        if (this.webSocket.readyState === 1) {
          this.webSocketSent("心跳检测")
        } else {
          // 重新连接
          this.reConnect()
        }
      }, this.timeout)
      this.serverTimeObject = setTimeout(() => {
        this.webSocket.close();
      }, this.timeout)
    },

    webSocketSent(msg) {
      this.webSocket.send(msg)
    },
    reConnect() {
      if (this.lockReconnect) {
        return;
      }
      this.lockReconnect = true;
      this.timeOutNum && clearTimeout(this.timeOutNum);
      this.timeOutNum = setTimeout(() => {
        this.initWebSocket();
        this.lockReconnect = false;
      }, 5000)
    },
    reSet() {
      this.timeObject && clearTimeout(this.timeObject);
      this.serverTimeObject && clearTimeout(this.serverTimeObject);
      // 重启心跳
      this.start();
    }
  }
}
</script>


<style scoped lang="scss">

</style>
